#!/usr/bin/env ruby -wKU
#encoding: utf-8

module DB_VTB
  
  require 'active_record'
  require 'backend/data/db'

  # create table if necessary, not sure what would happen if table is empty since I haven't test that yet
  # Note: this functinality may be shifted into db_impl.rb which uses ActiveRecord
  DB_VTB::SqliteImpl.new
  
  ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'w'))
  
  ActiveRecord::Base.establish_connection(
    adapter: 'sqlite3',
    database: $VALUABLE_TO_BUY_DB,
    encoding: 'utf-8'
  )
  
  if __FILE__ == $0
    
    # require 'backend/data/user'
    # require 'backend/data/interest'
    # require 'backend/data/notify'
#     
    # user = User.create(email: 'gjtiger@gmail.com', name: 'jun', password: 'jun')
    # user.save
#     
    # user = User.create(email: 'jugu@microstrategy.com', name: 'jun', password: 'jun')
    # user.save
#     
    # user = User.create(email: 'bwang@gmail.com', name: 'bin', password: 'bin')
    # user.save
#     
    # interest = Interest.create(uid: 1, value: 'TAOCP')
    # interest.save
#     
    # interest = Interest.create(uid: 1, value: 'MATH')
    # interest.save
#     
    # interest = Interest.create(uid: 3, value: '电饭煲')
    # interest.save
#     
    # users = User.all
    # users.each { |u|
      # puts u.id.to_s  + ", " + u.email + ", " + u.name + ", " + u.password
    # }
#     
    # user = nil
    # user = User.find_by(email: 'gjtiger@gmail.com')
    # puts user.id.to_s + ", " + user.email + ", " + user.name + ", " + user.password
    # user.interests.each { |i|
      # puts i.id.to_s + ", " + i.uid.to_s + ", " + i.value + ", " + i.notified.to_s + ", " + i.is_valid.to_s
    # }
#     
    # begin
      # ActiveRecord::Base.transaction {
        # interest = Interest.first
        # interest.notified = 1
        # interest.save!
#         
        # notify = Notify.create(iid: 1, url: "localhost:8080", time: Time.new.strftime("%Y-%m-%d %H:%M:%S"))
        # notify.save!
      # }
    # rescue ActiveRecord::RecordInvalid => invalid
      # puts "Error: #{invalid.class}, #{invalid.message}"
    # end
#     
    # user = nil
    # user = User.find_by(email: 'gjtiger@gmail.com')
    # puts user.id.to_s + ", " + user.email + ", " + user.name + ", " + user.password
    # user.interests.each { |i|
      # puts i.id.to_s + ", " + i.uid.to_s + ", " + i.value + ", " + i.notified.to_s + ", " + i.is_valid.to_s
    # }
#     
    # interest = Interest.first
    # interest.notifies.each { |n|
      # puts n.id.to_s + ", " + n.iid.to_s + ", " + n.url + ", " + n.time
    # }
#     
    # i = Interest.last
    # puts i.id.to_s + ", " + i.uid.to_s + ", " + i.value + ", " + i.notified.to_s + ", " + i.is_valid.to_s
    
  end
  
end